import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-08-03
 * Time: 22:01
 */
public class Fun {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer> map=new HashMap();
        for(int i=0;i<words.length;i++){
            if(map.get(words[i])==null){
                map.put(words[i],1);
            }
            else{
                int n=map.get(words[i]);
                map.put(words[i],n+1);
            }
        }
        PriorityQueue<Map.Entry<String,Integer>> pqueue=new PriorityQueue(new Comparator<Map.Entry<String,Integer>>() {
            @Override
            public int compare(Map.Entry<String,Integer> o1,Map.Entry<String,Integer> o2) {
                if(o1.getValue()== o2.getValue()){
                    return o2.getKey().compareTo(o1.getKey());
                }
                else{
                    return o1.getValue()-o2.getValue();
                }
            }
        });
        int n=1;
        for (Map.Entry<String,Integer> entry: map.entrySet()) {
            if(n<=k){
                pqueue.offer(entry);
                n++;
            }
            else{
                Map.Entry<String,Integer> root=pqueue.peek();
                if(fun(entry,root)){
                    pqueue.poll();
                    pqueue.offer(entry);
                }
            }
        }
        ArrayList<String> arr=new ArrayList<>();
        while(!pqueue.isEmpty()){
            arr.add(pqueue.poll().getKey());
        }
        Collections.reverse(arr);
        return arr;
    }

    public Boolean fun(Map.Entry<String,Integer> entry,Map.Entry<String,Integer> root){
        if(entry.getValue()>root.getValue()){
            return true;
        }
        if(entry.getValue()==root.getValue()&&entry.getKey().compareTo(root.getKey())<0){
            return true;
        }
        return false;
    }
}
